package com.nlx.notes.module.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JSONUtils {

    private static final  ObjectMapper objectMapper = new ObjectMapper(); ;
    static {
        objectMapper.registerModule(new JavaTimeModule());  // 注册 JavaTimeModule
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);  // 可选：忽略未知字段
        objectMapper.registerModule(new JavaTimeModule());
        // 可选：取消时间戳（默认会用 timestamp 表示日期）
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    public static String toString(Object data) {
        if(null == data){
            return null;
        }
        try {
            return objectMapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            log.error("序列化失败，错误信息 ->",e);
            return null;
        }
    }

    public static <T> T parse(String json, Class<T> clazz) {
        if(null == json){
            return null;
        }
        try {
            return objectMapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            log.error("序列化失败，错误信息 ->",e);
            return null;
        }

    }
}
